package si.yun.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.*;
import si.yun.entity.SyCarousel;
import si.yun.entity.SyPaySuccessInfo;
import si.yun.entity.SyUserOrderUsed;
import si.yun.service.HomeService;
import si.yun.utils.JsonData;
import si.yun.utils.MyRunnable;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

/**
 * @program: ThinkManage
 * @description: 首页web
 * @author: 崔晓晨
 * @create: 2021-10-15 09:28
 **/
@RestController
@RequestMapping("/home")
@PropertySource({"config/config.properties"})
public class HomeController {
    //连接业务层接口
    @Autowired
    private HomeService homeService;
    //获取服务器路径
    @Value("${path1}")
    private String path;
    //连接redis缓存
    @Autowired
    private RedisTemplate redisTemplate;

    //手动触发定时任务
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    //线程
    private ScheduledFuture<?> future1;
    private ScheduledFuture<?> future2;
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }
    /**
     * @Description  查询主页轮播图
     * @return si.yun.utils.JsonData
     * @Date 2021/10/14 16:45
     **/
    @GetMapping("/selCarouselInfo")
    public JsonData selCarouselInfo(){
        //redis缓存中获取
        ValueOperations<String,String> vo = redisTemplate.opsForValue();
        String value = vo.get("carousels");
        Gson gson = new Gson();
        List<SyCarousel> Carousels = gson.fromJson(value, List.class);
        //如果缓存中无数据去数据库中查
        if(Carousels!=null && Carousels.size()!=0){
            return Carousels!=null?JsonData.buildSuccess(Carousels):JsonData.buildError("服务器错误");
        }else{
            List<SyCarousel> syCarousels = homeService.selCarouselInfo();
            return syCarousels!=null?JsonData.buildSuccess(syCarousels):JsonData.buildError("服务器错误");
        }

    }
    /**
     * @Description  查找视频详情
     * @return si.yun.utils.JsonData
     * @Date 2021/10/15 9:33
     **/
    @GetMapping("/selCourseInfo")
    public JsonData selCourseInfo(){
        //redis缓存中获取
        ValueOperations<String,String> vo = redisTemplate.opsForValue();
        String value = vo.get("courseInfo");
        Gson gson = new Gson();
        List<Map<String, Object>> CourseInfo = gson.fromJson(value, List.class);
        //如果缓存中无数据去数据库中查
        if(CourseInfo!=null && CourseInfo.size()!=0){
            return CourseInfo!=null?JsonData.buildSuccess(CourseInfo):JsonData.buildError("服务器错误");
        }else{
            List<Map<String, Object>> list = homeService.selCourseInfo();
            return list!=null?JsonData.buildSuccess(list):JsonData.buildError("服务器错误");
        }
    }
    /**
     * @Description  获取课程的详细信息
     * @return si.yun.utils.JsonData
     * @Date 2021/10/26 11:32
     **/
    @PostMapping("/selCourseInformation")
    public JsonData selCourseInformation(Integer courseId){
        Map<String, Object> map = homeService.selCourseInformation(courseId);
        return map!=null?JsonData.buildSuccess(map):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  判断某一用户是否已经点赞
     * @return si.yun.utils.JsonData
     * @Date 2021/10/27 9:01
     **/
    @PostMapping("/selIfLikeNum")
    public JsonData selIfLikeNum(Integer userId, Integer courseId){
        Integer num =  homeService.selIfLikeNum(userId,courseId);
        //有点赞返回1   没有点赞情况返回0
        return JsonData.buildSuccess(num);
    }
    /**
     * @Description  点赞视频
     * @return si.yun.utils.JsonData
     * @Date 2021/10/27 11:50
     **/
    @PostMapping("/addLikeCourseNum")
    public JsonData addLikeCourseNum(Integer userId, Integer courseId){
        Integer add =  homeService.addLikeCourseNum(userId,courseId);
        return add!=0?JsonData.buildSuccess(add):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  取消点赞
     * @return si.yun.utils.JsonData 
     * @Date 2021/10/27 16:52
     **/
    @PostMapping("/delCourseLikeNum")
    public JsonData delCourseLikeNum(Integer userId, Integer courseId){
        Integer del = homeService.delCourseLikeNum(userId, courseId);
        return del!=0?JsonData.buildSuccess(del):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  判断用户是否收藏视频
     * @return si.yun.utils.JsonData
     * @Date 2021/10/27 19:21
     **/
    @PostMapping("/selColCourseIF")
    public JsonData selColCourseIF(Integer userId, Integer courseId){
        Integer num =  homeService.selColCourseIF(userId,courseId);
        //有点赞返回1   没有点赞情况返回0
        return JsonData.buildSuccess(num);
    }
    /**
     * @Description  收藏视频
     * @return si.yun.utils.JsonData
     * @Date 2021/10/27 19:21
     **/
    @PostMapping("/addColCourseInfo")
    public JsonData addColCourseInfo(Integer userId, Integer courseId){
        Integer add =  homeService.addColCourseInfo(userId,courseId);
        return add!=0?JsonData.buildSuccess(add):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  取消收藏
     * @return si.yun.utils.JsonData
     * @Date 2021/10/27 19:22
     **/
    @PostMapping("/delColCourseInfo")
    public JsonData delColCourseInfo(Integer userId, Integer courseId){
        Integer del = homeService.delColCourseInfo(userId, courseId);
        return del!=0?JsonData.buildSuccess(del):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  判断该用户是否分享过该视频
     * @return java.lang.Integer
     * @Date 2021/10/29 14:47
     **/
    @PostMapping("/selShareInfoIf")
    public JsonData selShareInfoIf(Integer userId, Integer courseId) {
        Integer ifNum = homeService.selShareInfoIf(userId, courseId);
        //有点赞返回值>1   没有点赞情况返回0
        return JsonData.buildSuccess(ifNum);
    }
    /**
     * @Description  插入分享数据
     * @return java.lang.Integer
     * @Date 2021/10/29 14:47
     **/
    @PostMapping("/addCourseShare")
    public JsonData addCourseShare(Integer userId, Integer courseId, Integer shareType) {
        Integer add = homeService.addCourseShare(userId, courseId, shareType);
        return add!=0?JsonData.buildSuccess(add):JsonData.buildError("服务器错误");
    }

    /**
     * @Description  获取当前课程下的相关目录
     * @return si.yun.utils.JsonData
     * @Date 2021/10/28 15:47
     **/
    @PostMapping("/selCourseClassInfo")
    public JsonData selCourseClassInfo(Integer courseId){
        List<Map<String, Object>> list = homeService.selCourseClassInfo(courseId);
        return list!=null?JsonData.buildSuccess(list):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  获取课程下的评论
     * @return si.yun.utils.JsonData 
     * @Date 2021/11/1 14:01
     **/
    @PostMapping("/selCourseComments")
    public JsonData selCourseComments(Integer courseId,Integer userId){
        List<Map<String, Object>> list = homeService.selCourseComments(courseId,userId);
        return JsonData.buildSuccess(list);
    }
    /**
     * @Description  点赞评论
     * @return si.yun.utils.JsonData
     * @Date 2021/11/1 18:53
     **/
    @PostMapping("/addCommentLike")
    public JsonData addCommentLike(Integer commentId,Integer userId,Integer courseId){
        Integer add = homeService.addCommentLike(commentId, userId, courseId);
        return add!=0?JsonData.buildSuccess(add):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  取消评论
     * @return si.yun.utils.JsonData
     * @Date 2021/11/1 18:59
     **/
    @PostMapping("/delCommentLike")
    public JsonData delCommentLike(Integer commentId,Integer userId,Integer courseId){
        //取消评论
        Integer delCommentLike = homeService.delCommentLike(commentId, userId, courseId);
        return delCommentLike!=0?JsonData.buildSuccess(delCommentLike):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  获取课程下的评论总数
     * @return si.yun.utils.JsonData
     * @Date 2021/11/1 19:36
     **/
    @PostMapping("/selCommentCountNum")
    public JsonData selCommentCountNum(Integer courseId){
        //获取课程下的评论总数
        Integer selCommentCountNum  = homeService.selCommentCountNum(courseId);
        return JsonData.buildSuccess(selCommentCountNum);
    }
    /**
     * @Description  添加留言
     * @return si.yun.utils.JsonData 
     * @Date 2021/11/2 10:10
     **/
    @PostMapping("/addCommentInfo")
    public JsonData addCommentInfo(Integer userId,Integer courseId,String content){
        Integer add = homeService.addCommentInfo(userId,courseId,content);
        return add!=0?JsonData.buildSuccess(add):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  删除个人评论 更改状态为删除 updCommentStatusDel
     * @return si.yun.utils.JsonData
     * @Date 2021/11/2 14:49
     **/
    @PostMapping("/updCommentStatusDel")
    public JsonData updCommentStatusDel(Integer commentId,Integer userId,Integer courseId){
        //删除个人评论 更改状态为删除
        Integer upd = homeService.updCommentStatusDel(commentId,userId,courseId);
        return upd!=0?JsonData.buildSuccess(upd):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  优惠券使用查询
     * @return si.yun.utils.JsonData
     * @Date 2021/11/4 11:11
     **/
    @PostMapping("/selCouponUserInfo")
    public JsonData selCouponUserInfo(Integer userId, Integer productType, BigDecimal courseNprice){

        Integer price = courseNprice.intValue();
        List<Map<String, Object>> list = homeService.selCouponUserInfo(userId, productType,price);
        if(list.isEmpty()){
            return JsonData.buildSuccess("暂无可用的优惠券");
        }else{
            return list!=null?JsonData.buildSuccess(list):JsonData.buildError("服务器错误");
        }
    }
    /**
     * @Description  获取个人拥有的不能使用的优惠券
     * @return si.yun.utils.JsonData
     * @Date 2021/11/4 11:11
     **/
    @PostMapping("/selAllCouponInfo")
    public JsonData selAllCouponInfo(Integer userId, Integer productType,BigDecimal courseNprice){
        Integer price = courseNprice.intValue();
        List<Map<String, Object>> list = homeService.selAllCouponInfo(userId, productType,price);
        if(list.isEmpty()){
            return JsonData.buildSuccess("暂无不可用的优惠券");
        }else{
            return list!=null?JsonData.buildSuccess(list):JsonData.buildError("服务器错误");
        }
    }
    /**
     * @Description  点击支付按钮生成订单
     * @return si.yun.utils.JsonData
     * @Date 2021/11/5 13:43
     **/
    @PostMapping("/addCourseOrder")
    public JsonData addCourseOrder(SyUserOrderUsed userOrder){
        System.out.println(userOrder+"==================================");
        System.out.println(userOrder.getUsedId());
        Integer add = homeService.addCourseOrder(userOrder);
        //开始执行定时器  查找超时订单信息的订单
        //startCron1();
        return add!=0?JsonData.buildSuccess(add):JsonData.buildError("服务器错误");
    }

    /**
     * @Description  付款成功后更改订单状态
     * @return java.lang.Integer
     * @Date 2021/11/8 10:23
     **/
    @PostMapping("/updCourseOrderStatus")
    public JsonData updCourseOrderStatus(SyPaySuccessInfo map) {
        Integer upd = homeService.updCourseOrderStatus(map);
        return upd!=0?JsonData.buildSuccess(upd):JsonData.buildError("服务器错误");
    }
    @PostMapping("/updCourseFreeOrderStatus")
    public JsonData updCourseFreeOrderStatus(SyPaySuccessInfo map) {
        Integer upd = homeService.updCourseFreeOrderStatus(map);
        return upd!=0?JsonData.buildSuccess(upd):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  更新用户消费金额
     * @return si.yun.utils.JsonData
     * @Date 2021/12/14 10:49
     **/
    @PostMapping("/updUserConsumption")
    public JsonData updUserConsumption(Integer userId,BigDecimal consumption) {
        Integer upd = homeService.updUserConsumption(userId,consumption);
        return upd!=0?JsonData.buildSuccess(upd):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  取消订单
     * @return si.yun.utils.JsonData
     * @Date 2021/11/12 13:42
     **/
    @PostMapping("/updOrderStatus")
    public JsonData updOrderStatus(Integer orderId,String remarks){
        Integer status = homeService.updOrderStatus(orderId, remarks);
        return status!=0?JsonData.buildSuccess(status):JsonData.buildError("服务器错误");
    }
    //测试手动触发定时任务
    public String startCron1() {
        //开始执行定时器  查找超时订单信息的订单
        future1 = threadPoolTaskScheduler.schedule(new MyRunnable(),new Trigger(){
            //0 0/15 * * * ?  15分钟执行一次
            //0/10 * * * * *  10秒执行一次
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext){
                List<Map<String, Object>> list = homeService.selWaitPayOrderInfo();
                if(list!=null && list.size()!=0){
                    Date nowDate = new Date();
                    for(Map<String, Object> map:list){
                        LocalDateTime ExpiredDate = (LocalDateTime) map.get("orderExpiredDate");
                        Date ExpiredDates = Date.from( ExpiredDate.atZone( ZoneId.systemDefault()).toInstant());
                        //1.具有转换功能的对象
                        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        String orderExpiredDate = df.format(ExpiredDate);
                        Integer orderId = (Integer) map.get("orderId");
//                        System.out.println(orderId+"==="+orderExpiredDate);
                        //即将超时的订单
                        if(nowDate.before(ExpiredDates)){
                            System.out.println("即将超时的订单"+orderId+"==="+orderExpiredDate);
                        }else{
                            //已经超时的订单
                            System.out.println("已经超时的订单"+orderId+"==="+orderExpiredDate);
                            //修改已经超时订单的状态
                            Integer upd = homeService.updOrderStatus(orderId, "订单超时，已自动取消");
                        }
                    }
                    return new CronTrigger("0 0/16 * * * ?").nextExecutionTime(triggerContext);
                }else{
                    //如果没有超时订单详情 关闭定时器
                    if (future1 != null) {
                        future1.cancel(true);
                    }
                    System.out.println("定时任务关闭");
                }
                return null;
            }
        });
        return "定时任务启动成功！";
    }
    /**
     * @Description  判断该用户是否拥有指定视频的播放资格
     * @return si.yun.utils.JsonData
     * @Date 2021/12/8 13:54
     **/
    @PostMapping("/getPlayQualifications")
    public JsonData getPlayQualifications(Integer userId,Integer productId){
        Map<String, Object> playQualifications = homeService.getPlayQualifications(userId, productId);
        return playQualifications!=null?JsonData.buildSuccess(playQualifications):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  更新课程的销量
     * @return si.yun.utils.JsonData
     * @Date 2021/12/21 16:56
     **/
    @PostMapping("/updcourseOrderNum")
    public JsonData updcourseOrderNum(Integer courseId){
        Integer upd = homeService.updcourseOrderNum(courseId);
        return upd!=0?JsonData.buildSuccess(upd):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  分享课程数量+1
     * @return si.yun.utils.JsonData
     * @Date 2021/12/21 16:56
     **/
    @PostMapping("/addCourseSharing")
    public JsonData addCourseSharing(Integer id){
        Integer upd = homeService.addCourseSharing(id);
        return upd!=0?JsonData.buildSuccess(upd):JsonData.buildError("服务器错误");

    }
    /**
     * @Description  查看教师的详细信息
     * @return si.yun.utils.JsonData
     * @Date 2021/12/29 18:06
     **/
    @PostMapping("/selTeaInfo")
    public JsonData selTeaInfo(Integer userId,Integer type){
        Map<String, Object> map = homeService.selTeaInfo(userId, type);
        return map!=null?JsonData.buildSuccess(map):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  查询指定人物的课程
     * @return si.yun.utils.JsonData
     * @Date 2021/12/29 18:49
     **/
    @PostMapping("/selCourseUserInfo")
    public JsonData selCourseUserInfo(Integer userId,Integer type){
        List<Map<String, Object>> list = homeService.selCourseUserInfo(userId, type);
        return list!=null?JsonData.buildSuccess(list):JsonData.buildError("服务器错误");
    }
    /**
     * @Description  添加商品订单时候，添加商品的收货地址
     * @return si.yun.utils.JsonData
     * @Date 2022/1/14 13:32
     **/
    @PostMapping("/selPrUserAddress")
    public JsonData selPrUserAddress(Integer userId){
        Map<String, Object> map = homeService.selPrUserAddress(userId);
        return map!=null?JsonData.buildSuccess(map):JsonData.buildError("服务器错误");
    }
}
